import React, { useEffect, useState } from 'react'
import SetTabBar from '@/components/tabBar'
import { SideBar, Ellipsis } from 'antd-mobile'
import { fetchCartList, fetchItems } from '@a/home'
import '../cate/style.scss'
import { useNavigate } from 'umi'
import Icon from '@c/Icon'
export default function index() {
  const navigate = useNavigate()
  const [lists , setLists] = useState<Array<{name: string, id: number}>>([])
  const [items, setItems] = useState<Array<{name: string, id: number,pic: string,minPrice: number}>>([])
  // 点击激活侧边栏
  const [activeIndex, setActiveIndex ] = useState(0)
  // 请求侧边导航信息
  const getCartList = () => {
    fetchCartList().then(res => {
      console.log(res);
      if (res.data.code === 0) {
        setLists(res.data.data)
      }
    })
  }
  // 初始化 分类数据赋值后 调用 初始化获取商品
  useEffect(() => {
    if (lists.length) {
      getFetchItems()
    }
  },[lists,activeIndex])
  // 请求商品信息
  const getFetchItems = () => {
    fetchItems({
      categoryId : lists[activeIndex].id
    }).then(res => {
      if (res.data.code === 0) {
        setItems(res.data.data.result)
      }
      if (res.data.code === 700) {
        setItems([])
      }
    })
  }
  useEffect(() => {
    getCartList()
  },[])
  return (
    <div>
      <div className="mian">
        <div className="mian-left">
          {/* 侧边导航 */}
          <SideBar activeKey={activeIndex} onChange={setActiveIndex}>
            {
              lists.map((list,index) => {
                return (
                  <SideBar.Item key={index} title={list.name} />
                )
              })
            }
        </SideBar>
        </div>
        <div className="mian-rig">
          {
            !items.length
            ?
            <div className='noShop'>暂无商品</div>
            :
            items.map(item => {
              return (
                <div className="item-box" key={item.id} onClick={() => {
                  navigate(`/detail/${item.id}`)
                }}>
                  <img src={item.pic} alt="" />
                  <div className="itenm-box-left">
                    <Ellipsis direction='end' content={item.name} />
                    <div className="itenm-box-left-bot">
                      <p>￥{item.minPrice}</p>
                      <div className="icon">
                        <Icon name='gouwuchetianjia' size={22} color={'white'}/>
                      </div>
                    </div>
                  </div>
                </div>
              )
            })
          }
        </div>
      </div>
      <SetTabBar/>
    </div>
  )
}
